import {
  AlipayCircleOutlined,
  LockOutlined,
  MailOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import { Tabs, Alert, message, Space } from 'antd';
import ProForm, { ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-form';
import type { MenuDataItem } from '@ant-design/pro-layout';
import { StateType } from '@/models/login';
import { connect } from 'umi';
import React, { useState } from 'react';
import { getFakeCaptcha, LoginParamsType } from '@/services/login';
import type { Dispatch, ConnectProps } from 'umi';
import type { FC } from 'react';
import type { ConnectState } from '@/models/connect';

import styles from './style.less';

export type LoginProps = {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
  breadcrumbNameMap: Record<string, MenuDataItem>;
} & Partial<ConnectProps>;

const LoginMessage: FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

export const Login: FC<LoginProps> = (props) => {
  const { 
    userLogin = {}, 
    submitting
  } = props;

  const { status, type: loginType } = userLogin;
  const [type, setType] = useState<string>('account');

  const handleSubmit = (values: LoginParamsType) => {
    const { dispatch } = props;
    dispatch({
      type: 'login/login',
      payload: { ...values, type },
    });
  };

  return (
    <div className={styles.main}>
      <ProForm
        initialValues={{
          autoLogin: true
        }}
        submitter={{
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            loading: submitting,
            size: 'large',
            style: {
              width: '100%'
            }
          }
        }}
        onFinish={(values) => {
          handleSubmit(values as LoginParamsType);
          return Promise.resolve();
        }}
      >
        <Tabs accessKey={type} onChange={setType}>
          <Tabs.TabPane key="account" tab="账户密码登录" />
          <Tabs.TabPane key="mobile" tab="手机号登录" />
        </Tabs>

        {status === 'error' && loginType === 'account' && !submitting && (
          <LoginMessage content="账户或密码错误" />
        )}
        {type === 'account' && (
          <>
            <ProFormText
              name="userName"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />
              }}
              placeholder="用户名: admin or user"
              rules={[
                {
                  required: true,
                  message: "请输入用户名！"
                }
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />
              }}
              placeholder="密码: ant.design"
              rules={[
                {
                  required: true,
                  message: "请输入密码！"
                }
              ]}
            />
          </>
        )}

        {status === 'error' && loginType === 'mobile' && !submitting && (
          <LoginMessage content="验证码错误！" />
        )}
        {type === 'mobile' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined className={styles.prefixIcon} />
              }}
              name="mobile"
              placeholder="手机号"
              rules={[
                {
                  required: true,
                  message: "请输入手机号！"
                },
                {
                  pattern: /^1\d{10}$/,
                  message: "手机号格式错误！"
                }
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: <MailOutlined className={styles.prefixIcon} />
              }}
              captchaProps={{
                size:'large'
              }}
              placeholder="请输入验证码"
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} 获取验证码`
                }
                return '获取验证码'
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！'
                }
              ]}
              onGetCaptcha={async (mobile) => {
                const result = await getFakeCaptcha(mobile);
                if (result === false) {
                  return;
                }
                message.success('获取验证码成功！验证码为：1234')
              }}
            />
          </>
        )}
        <div style={{ marginBottom: 24 }}>
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a style={{ float: 'right' }}>
            忘记密码
          </a>
        </div>
      </ProForm>
      <Space className={styles.other}>
        其他登录方式
        <AlipayCircleOutlined className={styles.icon} />
        <TaobaoCircleOutlined className={styles.icon} />
        <WeiboCircleOutlined className={styles.icon} />
      </Space>
    </div>
  )
}

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login']
}))(Login);